package com.manda.smart.hub.common.lambda;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * @author hongda.li
 */
public final class LazyLoader<T> {

    private final Supplier<T> supplier;

    private T result;

    private volatile boolean loaded = false;

    public LazyLoader(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public T get() {
        if (!this.loaded) {
            synchronized (LazyLoader.class) {
                this.result = supplier.get();
                this.loaded = true;
            }
        }
        return this.result;
    }

    public T getOrElse(T defaultValue) {
        return Optional.ofNullable(this.get()).orElse(defaultValue);
    }

    public T reload() {
        this.loaded = false;
        return this.get();
    }
}
